﻿using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;

/*
 * always use AudioSourceWrapper instead of AudioSource for short shoud clips.This way you'll get low latency audio sound
 */

public class AudioSourceWrapper : MonoBehaviour {
#if UNITY_ANDROID
	[DllImport("soundpoolhelper")]
	private static extern int LoadSound (String resId);
	[DllImport("soundpoolhelper")]
	private static extern void ClearSoundPool ();
	[DllImport("soundpoolhelper")]
	private static extern int PlaySound (int id, bool loop);
	[DllImport("soundpoolhelper")]
	private static extern void StopSound (int id);

	public bool useSoundPool;
	public String filePath;
	private int soundPoolId;
	private int streamId;
#endif

	public AudioSource source;

	// Use this for initialization
	void Start () {
#if UNITY_ANDROID
	if(useSoundPool)
	{
		soundPoolId = LoadSound(filePath);
		streamId = -1; // 避免误停其他通道的声音
	}
#else
		
#endif
	}
	
	// Update is called once per frame
	public void Play () {
#if UNITY_ANDROID
		if(useSoundPool)
			streamId = PlaySound(soundPoolId, false);
		else
			source.Play ();
#else
		Debug.Log("Play Sound");
		source.Play ();
#endif
	}

	public void Stop(){
#if UNITY_ANDROID
		if(useSoundPool)
		{
			if(-1 == streamId)
				return;

			StopSound(streamId);
			streamId = -1;
		}
		else
			source.Stop ();
#else
		source.Stop ();
#endif
	}
}
